/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/



import { Cascader } from 'antd';
import React, { FC, ReactNode } from 'react';
import { useEffect, useState } from 'react';
import style from './index.less';

// 其他属性类
type othProps = Record<string | number, any>;

// 选项类型
type Option = {
  // 选项值&*
  value: string | number;
  // 选项文本&*
  label: React.ReactNode | string | number;
  // 选项文本显示其他文本
  labelNum?: React.ReactNode | string;
  // 是否选项文本显示其他红点
  showDot?: boolean;
  disabled?: boolean;
  children?: Option[];
  // 标记是否为叶子节点，设置了 `loadData` 时有效
  // 设为 `false` 时会强制标记为父节点，即使当前节点没有 children，也会显示展开图标
  isLeaf?: boolean;
};

// 组件属性
type PropsOpt = othProps & {
  // 选项数据源&*
  carModelList: (Option | othProps)[];
  // option选项显示num：false关闭数字显示
  allOptionNum?: boolean;
  // option选项显示dot：false关闭点显示
  allOptionDot?: boolean;
  // 选中提交
  emitSelect?: (...props: any[]) => any;
  // 选中值
  carVal?: (string | number)[];
  // label显示
  labelNode?: ReactNode;
  // 其他配置属性
  othProps?: othProps;
};

// 选择后显示
const displayRender = (labels: any[]) => {
  // 过滤 ['', ''] 情况
  const newLabels = labels.filter(Boolean);
  if (newLabels.length) {
    // 判断数据第一个值是不是字符串
    if (typeof newLabels[0] === 'string') {
      return newLabels.join('/');
    }
    // 处理出来两个 ReactNode 数据
    const value = newLabels.map(label => label?.props?.children[0]);
    // 通过div 包裹 / 实现
    return <div className={style.customRender}>{value[0]} / {value[1]}</div>;
  }
  return ''
};

// label默认处理
const labelRNode: any = (
  label: ReactNode | string,
  item: Option,
  allOptionNum: boolean,
  allOptionDot: boolean,
) => {
  return (
    <div className={style.boxselect}>
      <span>{label}</span>
      {(item?.labelNum && allOptionNum && <span className={style.spannum}>{item?.labelNum}</span>) ||
        (item?.showDot && allOptionDot && <span className={style.spandot} />)}
    </div>
  );
};

// 数据源处理
const optionsData: any = (
  options: Option[],
  labelNode: any,
  fieldNames: any,
  allOptionNum: boolean,
  allOptionDot: boolean,
): any => {
  return options.map((item: Option) => {
    if (typeof item[fieldNames.label] == 'string') {
      try {
        item[fieldNames.label] = labelNode(
          item[fieldNames.label],
          item,
          allOptionNum,
          allOptionDot,
        );
      } catch (error) {
        console.log('error labelNode', labelNode);
      }
    }
    if (item[fieldNames.children] &&
      item[fieldNames.children].length)
      (item[fieldNames.children] = optionsData(
        item[fieldNames.children],
        labelNode,
        fieldNames,
        allOptionNum,
        allOptionDot,
      ));
    return item;
  });
};

const CarModelTreeSelect: FC<PropsOpt> = (props: PropsOpt) => {
  const {
    emitSelect = () => {
      // 设置选择的值
     },
    carModelList = [],
    carVal = [],
    labelNode = labelRNode,
    othProps = {},
    allOptionNum = true,
    allOptionDot = true,
  } = props;
  
  const [newOptions, setNewOptions] = useState([]);

  const { fieldNames = { label: 'label', value: 'value', children: 'children' } } = othProps;

  useEffect(() => {
    if (carModelList && carModelList.length) {
      const opsList = JSON.parse(JSON.stringify(carModelList));
      setNewOptions(optionsData(opsList, labelNode, fieldNames, allOptionNum, allOptionDot));
    } else {
      setNewOptions([])
    }
  }, [carModelList]);

  return (
    <Cascader
      options={newOptions}
      placeholder="请选择车型"
      expandTrigger="hover"
      value={carVal}
      dropdownClassName={style.CarModelTreeSelect}
      displayRender={displayRender}
      expandIcon={<span>{allOptionNum ? '' : '>'}</span>}
      onChange={(val) => emitSelect(val)}
      {...othProps}
    />
  );
};

export default CarModelTreeSelect;
